/* You may freely copy, distribute, and reuse the code in this example.
 * NeXT disclaims any warranty of any kind, expressed or  implied, as to its
 * fitness for any particular use.
 */


#import "Controller.h"
#import "FooObject.h"
#import "CellScrollView.h"
#import "FooCell.h"

@implementation Controller

- appDidInit:sender
{
  [self addFooObject:self];
  [cellScrollView loadCellsFrom:fooObjects];
  cellMatrix = [cellScrollView cellMatrix];
  return self;
}

- init
{
  [super init];
  fooObjects = [[List alloc] init];
  return self;
}

- free
{
  [fooObjects free];
  return [super free];
}

- addFooObject:sender
{
  FooObject *fooObject = [[FooObject alloc] init];
  [fooObjects addObject:fooObject];
  [cellScrollView loadCellsFrom:fooObjects];
  /*
   * Assumptions in this next line:
   *	There are as many fooCells as there are fooObjects
   *	We've added the new fooObject at the end of the list.
   *	We want to display the fooObject we just added and highlight it.
   * In short, this is a hack.
   */
  [cellMatrix scrollCellToVisible:[fooObjects count]-1 :0];
  [cellMatrix selectCellAt:[fooObjects count]-1:0];
  return self;
}

- deleteFooObjects:sender
/*
 * Delete all selected fooObjects.
 */
{
  int i;

  for (i=[cellMatrix cellCount]-1; i>=0; i--) {
    FooCell *cell = [cellMatrix cellAt:i:0];
    if ([cell isHighlighted]) {
      /*
       * If a cell is highlighted, remove (and free) the corresponding item
       * from the list of fooObjects.
       */
      [[fooObjects removeObject:[cell fooObject]] free];
    }
  }
  [cellScrollView loadCellsFrom:fooObjects];
  return self;
}

@end
